package com.woniu.ribbon.config;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.client.naming.core.Balancer;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.Server;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;

public class ClusterWeightRule extends AbstractLoadBalancerRule {
    @Autowired
    //拉入的依赖actuator就会暴露出信息，通过这个对象来获得
    private NacosDiscoveryProperties ndp;

    @Autowired
    //因为NacosDiscoveryProperties的获取服务节点的方法过期了，所以注入这个对象
    private NacosServiceManager nsm;

    @Override
    public Server choose(Object key) {
        //获取当前需要访问的服务名
        BaseLoadBalancer blb = (BaseLoadBalancer)getLoadBalancer();
        String serverName = blb.getName();
        //获取当前机器的服务信息
        //组名
        String groupName = ndp.getGroup();
        //集群名
        String clusterName = ndp.getClusterName();
        //去nacos上面获取该服务的节点
        NamingService ns = nsm.getNamingService(ndp.getNacosProperties());
        List<Instance> instances = null;
        //为了只查一次，少写try catch true为健康状态
        try {
            instances = ns.selectInstances(serverName, groupName, true);
        } catch (NacosException e) {
            try {
                instances = ns.selectInstances(serverName, "DEFAUT_GROUP", true);
            } catch (NacosException e1) {
                e1.printStackTrace();
            }
        }
        if(instances == null || instances.size() <= 0) return null;
        //过滤出与当前服务相同集群的节点，如果没有就直接用所有节点
        List<Instance> clusterInstances = instances.stream().filter(ins -> ins.getClusterName().equals(clusterName)).collect(Collectors.toList());
        if(clusterInstances == null || clusterInstances.size() <= 0) clusterInstances = instances;
        //在过滤出来的所有节点中按照权重算法选择一个返回
        Instance instance = RandomWeightRule.getRandomWeight(clusterInstances);
        //因为nacos返回类型是server 但是这里的返回对象是instance，nacosserver继承了server，
        //所以可以直接new
        return new NacosServer(instance);
    }

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {
    }

    //因为Balancer受保护的类，无法直接使用，所以在类里面继承以后，使用本类
    static class RandomWeightRule extends Balancer {
        public static Instance getRandomWeight(List<Instance> hosts) {
            return Balancer.getHostByRandomWeight(hosts);
        }
    }
}
